import baseURL from "./baseUrl";
import axios from "axios";
import ElementUI from "element-ui";

const instance = axios.create({
    baseURL: baseURL.url,
    timeout: 60000,
});

instance.interceptors.request.use(
    function (config) {
        config.headers.token = window.localStorage.getItem("ai_token");
        config.ContentType = "multipart/form-data";
        return config;
    },
    function (error) {
        return Promise.reject(error);
    }
);

// get请求
export function get(url, data, headers = {}) {
    return new Promise((resolve, reject) => {
        instance.get(url, data, { headers }).then((response) => {
            resolve(response);
        }).catch((error) => {
            reject(error);
        });
    });
}

// post请求
export function post(url, data = {}, headers = {}) {
    return new Promise((resolve, reject) => {
        instance.post(url, data, { headers }).then((response) => {
            resolve(response);
            if (response.data.code == -2) {
                ElementUI.Message.info(response.data.msg);
                window.localStorage.removeItem("ai_token");
                this.$router.push({ name: "login" });
            }
        }).catch((error) => {
            reject(error);
        });
    });
}

// 前端上传
export function ossUpload(file){
    return new Promise((resolve, reject) => {
        instance.post("/front/search/requestUpload").then(res=>{
            let ossRes = res.data.obj
            console.log(ossRes)
            let fileName = file.name
            let formData = new FormData()
            formData.append("key", ossRes.dir + "/" + fileName)
            formData.append("policy", ossRes.policy)
            formData.append("OSSAccessKeyId", ossRes.oSSAccessKeyId)
            formData.append("success_action_status", "200")
            formData.append("signature", ossRes.signature)
            formData.append("host", ossRes.host)
			formData.append("file", file)
            instance.post(ossRes.host, formData).then(()=>{
				let data = `${ossRes.host}/${ossRes.dir}/${fileName}`
				resolve(data)
            }).catch(()=>{
                reject("上传失败")
			})
        })
    })
}
